<form class="layui-form seller-form" action="">
    <div class="layui-form-item">

        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2" >时间范围：</label>
            <div class="layui-input-inline" >
                <input  type="text" name="date" value="" id="date" placeholder="请输入起止时间" autocomplete="off" class="layui-input">
            </div>
            <label class="layui-form-label layui-hide" >粒度：</label>
            <div class="layui-input-inline layui-hide" >
                <select name="section" id="section">
                    <option value="1">小时</option>
                    <option value="2">天</option>
                </select>
            </div>
            
            <label class="layui-form-label" >状态：</label>
            <div class="layui-input-inline" >
                <select name="status" id="status">
                    <option value="">全部</option>
                    <option value="成功">成功</option>
                    <option value="失败">失败</option>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <div class="">
                <button class="layui-btn layui-btn-sm"  val="" lay-submit lay-filter="*"><i class="iconfont icon-chaxun"></i>确定</button>
                <!-- <button class="layui-btn layui-btn-primary layui-btn-sm" val="1" lay-submit lay-filter="*">今日</button> -->
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="2" lay-submit lay-filter="*">昨日</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="3" lay-submit lay-filter="*">本周</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="4" lay-submit lay-filter="*">上周</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="5" lay-submit lay-filter="*">本月</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="6" lay-submit lay-filter="*">上月</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="7" lay-submit lay-filter="*">7日内</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="8" lay-submit lay-filter="*">一月内</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="9" lay-submit lay-filter="*">三月内</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="10" lay-submit lay-filter="*">半年内</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm"  val="11" lay-submit lay-filter="*">一年内</button>
                <button id="exportBtn" class="layui-btn layui-btn-sm layui-btn-disabled" lay-submit lay-filter="export-wxbill"><i
                    class="iconfont icon-clouddownload" style="font-size: 20px !important;" disabled></i>导出</button>  
            </div>
        </div>
    </div>

</form>

<div id="exportWxReconciliation" style="display: none;">
    <form class="layui-form export-form" action="">
        <div class="layui-form-item">
            <div class="layui-margin-10">
                <blockquote class="layui-elem-quote layui-text">
                    请先筛选要导出的记录，默认导出全部
                </blockquote>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">任务名称：</label>
                <input type="text" name="taskname" lay-verify="title" style="width:200px;" placeholder="请输入任务名称"
                    autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>
</div>

<div class="table-body">
    <table id="table" lay-filter="table"></table>
</div>
<script type="text/javascript">
    layui.use(['element','laydate','form','table'], function(){
        var element = layui.element;  
        var preDate = layui.util.toDateString(new Date(new Date()-1000*60*60*24), "yyyy-MM-dd");

        //时间插件
        layui.laydate.render({
            elem: '#date',
            range: '到',
            type: 'date',
            max: preDate,
            value: "{:date('Y-m-d')} 到 {:date('Y-m-d')}"
        });

        layui.form.on('submit(*)', function(data){
            type = data.elem.getAttribute('val');
            if(type != ""){
                if(type == 1 || type == 2) {
                    $('#section').val(1);
                } else {
                    $('#section').val(2);
                }

                getTime(type,function(){
                    device_balance();
                })
            }else{
                if($('#date').val() == '') {
                    layer.msg('【时间范围】不能为空', {time: 1300});
                    return false;
                }
 
                var values = $('#date').val().split("到");
                billingBeginDate = (values[0].trim());
                billingEndDate = (values[1].trim());
                if(billingBeginDate == billingEndDate){
                    $('#section').val(1);
                } else {
                    $('#section').val(2);
                }

                device_balance();
            }
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
  
        layui.form.on('submit(close)', function(data){
            layer.close(window.box);

            // 刷新对账信息
            device_balance();
        });

        layui.table.render({
                id: 'table'
                ,elem: '#table'
                ,title: '微信对账表'
                ,toolbar: '#toolbarBilling' //开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: []
                ,totalRow: true
                ,page: false //开启分页
                ,limit:'1000'
                ,cols: [[ //表头 
                    {type: 'checkbox', fixed: 'left'}
                    ,{field: 'x', title: '日期', width:120, totalRowText: '合计'}
                    ,{field: 'sys_num', title: '系统数量', width:120, totalRow: true, sort: true}
                    ,{field: 'sys_val', title: '系统金额', width:120, totalRow: true, sort: true}
                    ,{field: 'wx_num', title: '微信成功数量', width:140, totalRow: true, sort: true}
                    ,{field: 'wx_val', title: '微信成功金额', width:140, totalRow: true, sort: true}
                    ,{field: 'refund_wx_num', title: '微信退款数量', width:140, totalRow: true, sort: true}
                    ,{field: 'refund_wx_val', title: '微信退款金额', width:140, totalRow: true, sort: true}
                    ,{field: 'status', title: '状态', width:100, templet: '#statusTpl'}
                    ,{
                        field: 'option', title: '操作', templet: function (d) {
                            var html = '<a class="layui-btn layui-btn-xs view" date="' + d.x + '">查看详情</a>';
                            return html;
                        }, align: 'center', width: 100
                    }
                ]], //设置表头
                done: function(res, curr, count){
                    // 判断加载结果数量是否大于0
                    if(count>0){
                        $("#exportBtn").removeClass("layui-btn-disabled");
                        $('#exportBtn').removeAttr("disabled");
                    } else {
                        $('#exportBtn').addClass("layui-btn-disabled");
                        $('#exportBtn').attr("disabled", true);
                    }
                }
            });

        //编辑
        $(document).on('click', '.view', function () { 
            $date = $(this).attr('date');
            $hour = '';
            if($date.indexOf("时") != -1) {
                $hour = $date.substring(0, 2);
                var values = $('#date').val().split("到");
                $date = values[0].trim();
            }

            var url = "{:url('manage/Report/billDetailds')}" + '?date=' + $date + '&hour=' + $hour;
            var topLayui = parent === self ? parent.window.layui : top.parent.window.layui;
            topLayui.index.openTabsPage(url, '微信对账明细'); 
            return false;
        });

        //头工具栏事件
        layui.table.on('toolbar(table)', function(obj){
            var checkStatus = layui.table.checkStatus(obj.config.id);
            switch(obj.event){
            case 'rebill':
                var data = checkStatus.data;
                var billingDate = [];
                if(data.length > 0) {
                    if(data[0].x.indexOf("时") != -1) {
                        // 取当前时间
                        var values = $('#date').val().split("到");
                        billingDate.push(values[0].trim());
                    } else {
                        // 取选中的时间
                        for(i = 0; i < data.length; i++) {
                            billingDate.push(data[i].x); 
                        }
                    }
                }

                var dates = '';
                billingDate.forEach(function(x, index, a){
                    dates += x + ',';
                });
                dates = dates.substring(0, dates.length - 1);

                var beginDate = billingDate[0];
                var endDate = billingDate[billingDate.length-1];

                if(billingDate.length == 0){
                    layer.alert('尚未选择对账日期！');
                } else { 
                    layer.confirm(beginDate + '至' + endDate + ' 共'+ billingDate.length + '天，您确定要对账吗？', {
                        title: '提示', btn: ['确认', '取消'] //按钮
                    }, function(){ 
                        //添加弹出层
                        JsGet("{:url('Report/billingds')}?dates=" + dates, function (e) {
                            if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                                layer.msg(e.msg); return false;
                            }

                            window.box = layer.open({
                                type: 1,
                                content: e,
                                area: ['648px', '435px'],
                                title:'微信对账'
                            });
                        }) 
                    });
                }
            break;
            //自定义头工具栏右侧图标 - 提示
            case 'LAYTABLE_TIPS':
                layer.alert('这是工具栏右侧自定义的一个图标按钮');
            break;
            };
        });
        
        //取值
        function device_balance(){
            // 循环100毫秒等待
            var now = new Date();
            var exitTime = now.getTime() + 100;
            while (true) {
                now = new Date();
                if (now.getTime() > exitTime) {
                    if($('#date').val() != '') {
                        break;
                    }
                    exitTime = now.getTime() + 100;
                }
            }
            
            var data = {
                date: $('#date').val(),
                section:$('#section').val(),
                status:$('#status').val()
            };
            JsPost("", data, function(res){ 
                if(res.status){
                    //刷新table
                    layui.table.reload('table',{
                        data: res.data
                    }); 
                }else{
                    layer.msg(res.msg);
                }
            });
        }
        //解析时间按钮
        function getTime(type,calback){
            var data = {
                date_type:type
            };
            
            JsPost('{:url("getDateTypeEx")}', data, function(res){
                if(res.status){
                    //设置时间，回调
                    $('#date').val(res.data.start  + " 到 " + res.data.end);
                    calback();
                }else{
                    layer.msg(res.msg);
                }
            })
        }

        //微信账单导出
        layui.form.on('submit(export-wxbill)', function (data) {
            layer.open({
                type: 1,
                title: '微信对账明细导出',
                area: ['400px', '248px'], //宽高`
                btn: ['确定', '取消'],
                content: $("#exportWxReconciliation").html(),
                success: function () {
                    $(':focus').blur();
                    this.enterEsc = function(event){
                        if(event.keyCode === 13){
                            if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                                $(".layui-layer-btn0").addClass("layui-btn-disabled");

                                //判断是否有选中
                                var filter = $(".seller-form").serialize(); 
                                $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                                var data = $(".export-form:last").serializeArray();
                                
                                if($.trim(data[0]['value']) == '') {
                                    layer.msg('请填写任务名称！', { time: 1300 });
                                    $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                    return false;
                                }

                                data.push({ 'name': 'model', 'value': 'WxReconciliationDs' });
                                JsPost("{:url('Ietask/export')}", data, function (res) {
                                        layer.msg(res.msg, { time: 1500 }, function () {
                                            if (res.status) {
                                                layer.closeAll();
                                                //执行跳转
                                                var topLayui = parent === self ? layui : top.layui;
                                                topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                            } else {
                                                $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                            }
                                        });
                                    }
                                );
                            }
                            return false; //阻止系统默认回车事件
                        }
                    };
                    $(document).on('keydown', this.enterEsc);	//监听键盘事件，关闭层
                },
                yes: function () {
                    if(!$(".layui-layer-btn0").hasClass("layui-btn-disabled")){
                        $(".layui-layer-btn0").addClass("layui-btn-disabled");

                        //判断是否有选中
                        var filter = $(".seller-form").serialize(); 
                        $(".export-form:last").append("<input type='hidden' name='filter' value='" + filter + "'>");
                        var data = $(".export-form:last").serializeArray();
                        
                        if($.trim(data[0]['value']) == '') {
                            layer.msg('请填写任务名称！', { time: 1300 });
                            $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                            return false;
                        }

                        data.push({ 'name': 'model', 'value': 'WxReconciliationDs' });
                        JsPost("{:url('Ietask/export')}", data, function (res) {
                                layer.msg(res.msg, { time: 1500 }, function () {
                                    if (res.status) {
                                        layer.closeAll();
                                        //执行跳转
                                        var topLayui = parent === self ? layui : top.layui;
                                        topLayui.index.openTabsPage('/manage/ietask/index.html', '导入导出');
                                    } else {
                                        $(".layui-layer-btn0").removeClass("layui-btn-disabled");
                                    }
                                });
                            }
                        );
                    }
                }, btn2: function () {
                    layer.closeAll();
                }, end: function(){
                    $(document).off('keydown', this.enterEsc);	        //解除键盘关闭事件
                }
            });
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        // 取昨天作为默认时间
        getTime(2,function(){
            device_balance();
        })
    });

</script>
<script type="text/html" id="statusTpl">
    {{#  if(d.status === '成功'){ }}
        <span class="layui-bg-green">{{ d.status }}</span>
    {{#  } else { }}
        <span class="layui-bg-red">{{ d.status }}</span>
    {{#  } }}
</script>

<script type="text/html" id="toolbarBilling">
    <div class="layui-btn-container">
      <button class="layui-btn layui-btn-sm" lay-event="rebill">对账</button>
    </div>
</script>